package dou;

import java.util.concurrent.TimeUnit;

public class theat {
    public static void main(String[] args) {
        Ticket t = new Ticket(20);
        Thread t1 = new Thread(t, "北京");
        Thread t2 = new Thread(t, "上海");
        Thread t3 = new Thread(t, "广东");
        Thread t4 = new Thread(t, "深圳");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

}

class Ticket implements Runnable {
    private int num = 0;

    public Ticket(int num) {
        this.num = num;
    }

    @Override
    public void run() {
        while (true) {
            synchronized (this) {
                if (num > 0) {
                    System.out.printf("[%s]售出一张票，剩余%d张票%n", Thread.currentThread().getName(), --num);
                } else {
                    System.out.printf("[%s]票已售空，停止售票。", Thread.currentThread().getName());
                    break;
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
